const clockElement = document.getElementById("clock");

function updateClock() {
  const now = new Date();
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");

  clockElement.textContent = `${hours}:${minutes}:${seconds}`;
  // setClock();
}

function setClock() {
  const now = new Date();
  const secondsRatio = now.getSeconds() / 60;
  const minutesRatio = (secondsRatio + now.getMinutes()) / 60;
  const hoursRatio = (minutesRatio + now.getHours()) / 12;

  const secondHand = document.querySelector(".second-hand");
  const minuteHand = document.querySelector(".minute-hand");
  const hourHand = document.querySelector(".hour-hand");

  setTransform(secondHand, 360 * secondsRatio);
  setTransform(minuteHand, 360 * minutesRatio);
  setTransform(hourHand, 30 * hoursRatio);
}

function setTransform(element, rotation) {
  element.style.transform = `translate(-100%, -100%) rotate(${rotation}deg)`;
}

setInterval(updateClock, 100);
updateClock();
// setClock();

//向iframe发送键盘事件
document.addEventListener("keydown", function (event) {
  if (event.target.tagName !== "INPUT" && event.target.id !== "display") {
    let key = event.key;
    if (!isNaN(key) && key >= "0" && key <= "9") {
      sendKeyEventToIframe(key);
    } else if (["+", "-", "*", "/"].includes(key)) {
      sendKeyEventToIframe(key);
    } else if (key === "c" || key === "C") {
      sendKeyEventToIframe(key);
    } else if (key === "=" || key === "Enter") {
      sendKeyEventToIframe(key);
    } else if (key === "Backspace") {
      sendKeyEventToIframe(key);
    }
    event.preventDefault();
  }
});

function sendKeyEventToIframe(keycontent) {
  var iframe = document.getElementById("myIframe");

  if (iframe.contentWindow && iframe.contentWindow.postMessage) {
    var message = {
      type: "keyEvent",
      key: keycontent,
    };

    iframe.contentWindow.postMessage(message, "*");
  } else {
    console.error("Iframe不可用或不支持postMessage");
  }
}
